package hello.app.util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GoogleSearch{

	private static final String WEB_SEARCH_ENDPOINT = "http://ajax.googleapis.com/ajax/services/search/web";

	public class Result{
		private String title;
		private String content;
		private String url;

		protected Result(){

		}

		public String getTitle() {
			return title;
		}
		public void setTitle(String title) {
			this.title = title;
		}
		public String getContent() {
			return content;
		}
		public void setContent(String content) {
			this.content = content;
		}

		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
	}

	private class ResponseHandlerEx implements ResponseHandler<String>{
		ResponseCallback mHandler;

		ResponseHandlerEx(ResponseCallback handler){
			mHandler = handler;
		}
		public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity httpEntity = response.getEntity();
				String json = EntityUtils.toString(httpEntity);
				try {
					mHandler.handleResponse(getSearchResults(json));
				} catch (JSONException e) {
					mHandler.handleResponse(null);
				}
			}
			return null;
		}

	}

	public interface ResponseCallback{
		public void handleResponse(Result[] results);
	}

	public GoogleSearch() {
	}

	public Result[] getResult(String query) throws JSONException, ParseException, IOException, URISyntaxException{
		String url = WEB_SEARCH_ENDPOINT + "?v=1.0&q=" + query;
		String json = null;
		HttpResponse response = null;
		DefaultHttpClient client = new DefaultHttpClient();
		URI uri = new URI(url);
		HttpUriRequest request = new HttpGet(uri);
		response = client.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity httpEntity = response.getEntity();
			json = EntityUtils.toString(httpEntity);
		}
		client.getConnectionManager().shutdown();
		Result[] ret = getSearchResults(json);
		return ret;
	}

	public void asynchronousRequest(String query, ResponseCallback handler) throws URISyntaxException, ClientProtocolException, IOException{
		String url = WEB_SEARCH_ENDPOINT + "?v=1.0&q=" + query;
		DefaultHttpClient client = new DefaultHttpClient();
		URI uri = new URI(url);
		HttpUriRequest request = new HttpGet(uri);
		client.execute(request, new ResponseHandlerEx(handler));
	}

	private Result[] getSearchResults(String json) throws JSONException{
		JSONObject jsonObject = new JSONObject(json);
		JSONArray jsonResults = jsonObject.getJSONObject("responseData").getJSONArray("results");
		Result[] results = new Result[jsonResults.length()];
		for(int i = 0; i < jsonResults.length(); i++){
			results[i] = getSearchResultByJSON(jsonResults.getJSONObject(i));
		}
		return results;
	}

	private Result getSearchResultByJSON(JSONObject result) throws JSONException{
		Result ret = new Result();
		ret.setTitle(result.getString("title"));
		ret.setContent(result.getString("content"));
		ret.setUrl(result.getString("url"));
		return ret;
	}


}
